package com.enation.app.javashop.core.promotion.shetuan.service.impl;

import com.enation.app.javashop.core.goods.model.enums.Permission;
import com.enation.app.javashop.core.goods.model.vo.BackendGoodsVO;
import com.enation.app.javashop.core.goods.service.GoodsManager;
import com.enation.app.javashop.core.promotion.PromotionErrorCode;
import com.enation.app.javashop.core.promotion.activitymessage.model.dos.ActivityMessageDO;
import com.enation.app.javashop.core.promotion.activitymessage.model.dos.ActivityMessageRecordDO;
import com.enation.app.javashop.core.promotion.activitymessage.service.ActivityMessageManager;
import com.enation.app.javashop.core.promotion.shetuan.model.ShetuanVO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanDO;
import com.enation.app.javashop.core.promotion.shetuan.model.dos.ShetuanGoodsDO;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanGoodsStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.model.enums.ShetuanStatusEnum;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanGoodsOperateManager;
import com.enation.app.javashop.core.promotion.shetuan.service.ShetuanManager;
import com.enation.app.javashop.core.statistics.util.DateUtil;
import com.enation.app.javashop.framework.database.DaoSupport;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.util.BeanUtil;
import com.enation.app.javashop.framework.util.StringUtil;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 社区团购服务
 *
 * @author admin
 * @version vv1.0.0
 * @since vv7.1.0
 * 2019-01-21 15:17:57
 */
@Service
public class ShetuanManagerImpl implements ShetuanManager {
    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    @Qualifier("tradeDaoSupport")
    private DaoSupport tradeDaoSupport;

    @Autowired
    private ShetuanGoodsManager shetuanGoodsManager;
    @Autowired
    private ActivityMessageManager activityMessageManager;
    @Autowired
    private GoodsManager goodsManager;
    @Autowired
    private ShetuanGoodsOperateManager shetuanGoodsOperateManager;


    @Override
    public List<ShetuanDO> get(String status) {
        return null;
    }

    @Override
    public Page<ShetuanDO> getPageBySellerId(Integer pageSize, Integer pageNo, Integer sellerId) {
        String sql = "select * from es_shetuan  where seller_id=?  order by create_time desc";
        Page page = tradeDaoSupport.queryForPage(sql, pageNo, pageSize, ShetuanDO.class, sellerId);
        List<ShetuanDO> shetuanDOList = page.getData();
        List<ShetuanVO> shetuanVOList = new ArrayList<>();
        for (ShetuanDO shetuanDO : shetuanDOList) {
            ShetuanVO  shetuanVO = new ShetuanVO();
            BeanUtil.copyProperties(shetuanDO,shetuanVO);
            Integer shetuanId = shetuanVO.getShetuanId();
            // 查询订阅人数
            List<ActivityMessageRecordDO> activityMessageRecordDOList = activityMessageManager.getActivityMessageRecordDO(shetuanId);
            if(StringUtil.isNotEmpty(activityMessageRecordDOList)){
                shetuanVO.setSubscribersNum(activityMessageRecordDOList.size());
            }else {
                // 订阅人数
                shetuanVO.setSubscribersNum(0);
            }

            shetuanVOList.add(shetuanVO);
        }
        page.setData(shetuanVOList);
        return page;
    }

    @Override
    @Transactional
    public ShetuanDO add(ShetuanDO shetuanDO) {
        // 活动编码
        Date date = new Date(shetuanDO.getStartTime() * 1000);
        String no = shetuanDO.getSellerId() + "_" + DateFormatUtils.format(date, "yyyyMMdd") + DateFormatUtils.format(new Date(), "_HHmmss");
        shetuanDO.setShetuanNo(no);
        // 活动初始状态 待上线
        shetuanDO.setStatus(ShetuanStatusEnum.NEW.getIndex());
        shetuanDO.setCreateTime(DateUtil.getDateline());
        this.tradeDaoSupport.insert("es_shetuan", shetuanDO);
        shetuanDO.setShetuanId(this.tradeDaoSupport.getLastId("es_shetuan"));
        return shetuanDO;
    }

    @Override
    public   List<ShetuanDO>  getOverlapShetuan( Integer shetuanId ) {
        ShetuanDO shetuan = this.getShetuanById(shetuanId);
        if (shetuan.getStartTime() == null || shetuan.getEndTime() == null) {
            throw new ServiceException(PromotionErrorCode.E400.code(), "该社区团购开始时间或者结束时间为空");
        }
        Integer sellerId = shetuan.getSellerId();
        Long startTime=shetuan.getStartTime();
        Long endTime=shetuan.getEndTime();
        /**
         * *************第一、两种情况：******************
         * 本团购时间段：      |________________|
         * 其他团购时间段：  |_____|           |_______|
         *
         * ************第三种情况：******************
         * 本团购时间段：        |______|
         * 其他团购时间段：   |________________|
         *
         * ************第四种情况：******************
         * 本团购时间段：   |________________|
         * 其他团购时间段：        |______|
         */


        String sql = "select * from es_shetuan where status= ? and seller_id=? and (" +
                " ( start_time<?  && end_time>? )" +
                " || ( start_time<?  && end_time>? )" +
                " || ( start_time<?  && end_time>? )" +
                " || ( start_time>?  && end_time<? ))";


        List<ShetuanDO> shetuanDOS = tradeDaoSupport.queryForList(sql, ShetuanDO.class,ShetuanStatusEnum.ON_LINE.getIndex(),sellerId,
                startTime, startTime,
                endTime, endTime,
                startTime, endTime,
                startTime, endTime
        );

        return shetuanDOS;
    }

    @Override
    public ShetuanDO getShetuanById(Integer shetuanId) {
        String sql = "select * from es_shetuan  where shetuan_id=?";
        ShetuanDO shetuanDO = tradeDaoSupport.queryForObject(sql, ShetuanDO.class, shetuanId);
        return shetuanDO;
    }


    @Override
    public ShetuanVO getShetuanDetailFromDB(Integer shetuanId) {
        String sql = "select * from es_shetuan  st where st.shetuan_id=?";
        ShetuanVO shetuanVO = tradeDaoSupport.queryForObject(sql, ShetuanVO.class, shetuanId);
        if (shetuanVO != null) {
            String sqlGoods = "select * from es_shetuan_goods  sg where sg.shetuan_id=? and sg.status !=?";
            List<ShetuanGoodsDO> shetuanGoods = tradeDaoSupport.queryForList(sqlGoods, ShetuanGoodsDO.class, shetuanId,ShetuanGoodsStatusEnum.DELETE.getIndex());
            shetuanVO.setShetuanGoodsList(shetuanGoods);
        }
        return shetuanVO;
    }


    @Override
    public void edit(ShetuanDO shetuanDO) {
        // 修改了开始时间需要判断活动是否处于自动待触发状态
        ShetuanDO oldShetuan = this.getShetuanById(shetuanDO.getShetuanId());
        if(!oldShetuan.getStartTime().equals(shetuanDO.getStartTime()) && oldShetuan.getStatus()!=ShetuanStatusEnum.ON_LINE.getIndex()){
            shetuanDO.setStatus(ShetuanStatusEnum.NEW.getIndex());
        }
        shetuanDO.setUpdateTime(DateUtil.getDateline());
        this.tradeDaoSupport.update(shetuanDO, shetuanDO.getShetuanId());

    }


    /**
     * 开始团购报名
     *
     * @param shetuanId
     */
    @Override
    public void startSignUp(Integer shetuanId) {
        ShetuanDO shetuanDO = this.tradeDaoSupport.queryForObject(ShetuanDO.class, shetuanId);
        //设置成开始报名
        shetuanDO.setStatus(ShetuanStatusEnum.SIGN_UP.getIndex());
        this.tradeDaoSupport.update(shetuanDO, shetuanId);

    }


    @Override
    public void delete(Integer shetuanId) {
        ShetuanDO shetuanDO = this.tradeDaoSupport.queryForObject(ShetuanDO.class, shetuanId);
        if (shetuanDO == null) {
            throw new ServiceException(PromotionErrorCode.E402.code(),"活动不存在！");
        }
        if (shetuanDO.getEndTime()>DateUtil.getDateline()) {
            throw new ServiceException(PromotionErrorCode.E402.code(),"活动尚未结束，不能删除！");
        }
        //设置成待上线
        shetuanDO.setStatus(ShetuanStatusEnum.DELETE.getIndex());
        this.tradeDaoSupport.update(shetuanDO, shetuanId);
    }


    @Override
    @Transactional(value = "tradeTransactionManager", propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void deleteNewStatus(Integer shetuanId) {
        ShetuanDO shetuanDO = this.tradeDaoSupport.queryForObject(ShetuanDO.class, shetuanId);
        if (shetuanDO == null) {
            throw new ServiceException(PromotionErrorCode.E402.code(),"活动不存在！");
        }
        if (shetuanDO.getStatus() == null || ShetuanStatusEnum.NEW.getIndex() != shetuanDO.getStatus()) {
            throw new ServiceException(PromotionErrorCode.E402.code(),"此活动不可删除");
        }
        //物理删除shetuan和shetuan_goods表
        this.tradeDaoSupport.delete(ShetuanDO.class, shetuanId);
        this.tradeDaoSupport.execute("delete from es_shetuan_goods where shetuan_id=?", shetuanId);
    }

    @Override
    public List<ShetuanDO> getShetuanIdBySellerId(Integer sellerId) {
        long nowTime = com.enation.app.javashop.framework.util.DateUtil.getDateline();
        String sql = "SELECT * from es_shetuan where seller_id = ? and start_time <= ? and end_time >= ? and page_popup = 1 and `status` = 40 ORDER BY create_time desc ;";
        return tradeDaoSupport.queryForList(sql,ShetuanDO.class,sellerId,nowTime,nowTime);
    }

}
